import {
  VuexModule,
  Mutation,
  Action,
  getModule,
  Module
} from 'vuex-module-decorators'
import store from '@/store'
import elementVariables from '@/assets/style/element-variables.scss'
import defaultSettings from '../types/setting'
import { dbSet, dbGet, dbStoreName } from '@/libs/util.db'

export interface ISettingsState {
  theme: string;
  showSettings: boolean;
  sidebarTextTheme: boolean
}
// 设置常量
const THEME = 'theme'
const SHOW_SETTINGS = 'showSettings'
const SIDERBAR_TEXT_THEME = 'sidebarTextTheme'

@Module({ dynamic: true, store, name: 'settings' })
class Settings extends VuexModule implements ISettingsState {
  public theme = dbGet({ dbName: dbStoreName.sys, path: THEME }) || elementVariables.theme // 主题颜色
  public showSettings = dbGet({ dbName: dbStoreName.sys, path: SHOW_SETTINGS }) // 是否显示系统设置开关
  public sidebarTextTheme = dbGet({ dbName: dbStoreName.sys, path: SIDERBAR_TEXT_THEME })

  @Mutation
  private CHANGE_SETTING (payload: { key: string; value: any }) {
    const { key, value } = payload
    if (Object.prototype.hasOwnProperty.call(this, key)) {
      (this as any)[key] = value
      dbSet({ dbName: dbStoreName.sys, path: key, value }) // 持久化保存系统默认设置
    }

    // if(key === 'theme') {
    //   dbSet({ dbName: 'sys', path: 'theme', value })
    // }
  }

  get showSettingss (): boolean {
    return this.showSettings
  }

  get themee (): string {
    return this.theme
  }

  get sidebarTextThemee (): boolean {
    return this.sidebarTextTheme
  }

  @Action
  public ChangeSetting (payload: { key: string; value: any }) {
    this.CHANGE_SETTING(payload)
  }

  @Action
  public InitSetting () {
    this.CHANGE_SETTING({ key: THEME, value: elementVariables.theme })
    this.CHANGE_SETTING({ key: SHOW_SETTINGS, value: defaultSettings.showSettings })
    this.CHANGE_SETTING({ key: SIDERBAR_TEXT_THEME, value: defaultSettings.sidebarTextTheme })
  }
}

export const SettingsModule = getModule(Settings)
